/*
 * Copyright (C) 2012  Romain DUBOIS
 * 
 * This file is part of NeMoS - Network and Modular Software
 * 
 * NeMoS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * NeMoS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with NeMoS.  If not, see <http://www.gnu.org/licenses/>.
 */
package nemos.swing.swixml.customization;

import java.util.Locale;
import java.util.MissingResourceException;

import nemos.util.i18n.ITranslator;

import org.swixml.Localizer;

/**
 * NemosLocalizer : The customized localizer.
 * 
 * @author Romain DUBOIS
 */
public class NemosLocalizer extends Localizer {

    /** The translator to use */
    private final ITranslator mTranslator;
    /** The labels base name */
    private String mBaseName;
    /** The current locale */
    private Locale mLocale;

    /**
     * Constructor.
     * 
     * @param pTranslator
     *            The translator to use
     */
    public NemosLocalizer(final ITranslator pTranslator) {
        super();
        mTranslator = pTranslator;
    }

    /**
     * {@inheritDoc}
     * 
     * @see org.swixml.Localizer#getString(java.lang.String)
     */
    @Override
    public String getString(final String pKey) {
        if (mTranslator == null || pKey == null || pKey.isEmpty() || pKey.charAt(0) != '%') {
            return pKey;
        }

        // Delegate to translator service
        return mTranslator.translateLabel(mBaseName, pKey.substring(1), mLocale);
    }

    /**
     * {@inheritDoc}
     * 
     * @see org.swixml.Localizer#isUsable()
     */
    @Override
    public boolean isUsable() {
        return mTranslator != null;
    }

    /**
     * {@inheritDoc}
     * 
     * @see org.swixml.Localizer#setLocale(java.util.Locale)
     */
    @Override
    public void setLocale(final Locale locale) {
        mLocale = locale;
    }

    /**
     * {@inheritDoc}
     * 
     * @see org.swixml.Localizer#setResourceBundle(java.lang.String)
     */
    @Override
    public void setResourceBundle(final String bundleName) throws MissingResourceException {
        mBaseName = bundleName;
    }

    /**
     * Get the current locale.
     * 
     * @return The current locale
     */
    public Locale getLocale() {
        return mLocale;
    }
}
